<?php
session_start();
set_include_path('./../../nearestCaches/library' . PATH_SEPARATOR . get_include_path());
$PEAR_PATH = 'PEAR.php';
include ('Request/Request.php');
include "functions.php";
$lang = getLang();
$versionInt = getClientIntVersion();

global $viewstate;
global $postback;
global $cookie;

//get page of selected cache
$url = "http://www.geocaching.com/seek/cache_details.aspx?guid=".$_GET['guid'];
$req = & new HTTP_Request($url);
$req->setMethod(HTTP_REQUEST_METHOD_GET);
$req->addHeader('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6');
$req->addCookie('ASP.NET_SessionId', $_SESSION['cookie']);
$req->sendRequest();
$response = $req->getResponseBody();

//getting cache coordinates and other info needed for navigate
$position = 0;
$coordinates = parseBetween('<span id="ctl00_ContentBody_LatLon" style="font-weight:bold;">', '</span>');
$coords = explode(' ', $coordinates);
$coordinates = $coords[0]. ' '.$coords[1]. ' '.$coords[2]. '<br />'.$coords[3]. ' '.$coords[4]. ' '.$coords[5];

$lat_h = $coords[0];
$lat_d = substr($coords[1], 0, 2);
$lat_m = $coords[2];

$lon_h = $coords[3];
$lon_d = substr($coords[4], 0, 3);
$lon_m = $coords[5];

//converting coordinates to requested format
$lat = latDMtoD($lat_h, $lat_d, $lat_m);
$lon = lonDMtoD($lon_h, $lon_d, $lon_m);

//cache info which we add to kml
$position = 0;
$oldResponse = $response;
$response = parseBetween('<div id="ctl00_cacheCodeWidget" class="CacheCodeWidget">', '</div>');
$position = 0;
$waypoint = trim(parseBetween('<p>', '</p>'));
$position = 0;
$response = $oldResponse;
$response = parseBetween('<h2 class="NoSpacing"><a href="/about/cache_types.aspx" target="_blank" title="About Cache Types">', '<table class="CacheInformationTable Spacing">');
$position = 0;
$typeNumber = parseBetween('WptTypes/', '.gif');
$type = parseBetween('alt="', '" width');
$cacheName = parseBetween('<span id="ctl00_ContentBody_CacheName">', '</span>');
$cacheName = html_entity_decode($cacheName,ENT_NOQUOTES,"UTF-8");
$position = strpos($response, '<span id="ctl00_ContentBody_CacheOwner">by <a href="')+52;
$author = parseBetween('">', '</a>');
$author = str_replace("&", "&amp;", $author);
$hidden = parseBetween('<span id="ctl00_ContentBody_DateHidden">', '</span>');
$size = parseBetween('gif" alt="Size: ', '" />');
$position = strpos($response, '<span id="ctl00_ContentBody_Difficulty">')+40;
$difficulty = parseBetween('gif" alt="', ' out of ');
$position = strpos($response, '<span id="ctl00_ContentBody_Terrain">')+38;
$terrain = parseBetween('gif" alt="', ' out of ');
$description = "$type, $difficulty/$terrain, $size, $waypoint";
if ($versionInt >= 151) //links for offline caches
{
    //test if this cache have additional waypoints
    $isAW = strpos($oldResponse, '<strong>Additional Waypoints</strong>');

    $description .= '<br /><a href="'.SERVICE_URL.'cache.php?show=listing&amp;guid='.$_GET['guid'].'">'.$lang['show_listing'].'</a><br />
                        <a href="'.SERVICE_URL.'cache.php?show=hint&amp;guid='.$_GET['guid'].'">'.$lang['show_hint'].'</a><br />
                        <a href="'.SERVICE_URL.'cache.php?show=logs&amp;guid='.$_GET['guid'].'">'.$lang['show_logs'].'</a><br />
                        <a href="'.SERVICE_URL.'log.php?type=offline&amp;guid='.$_GET['guid'].'">'.$lang['log_visit'].'</a><br />
                        <a href="'.SERVICE_URL.'waypoint_navigate.php">'.$lang['wpnav'].'</a>';
    $urls = SERVICE_URL.'cache.php?show=listing&guid='.$_GET['guid'].' '.SERVICE_URL.'cache.php?show=hint&guid='.$_GET['guid'].' '.SERVICE_URL.'cache.php?show=logs&guid='.$_GET['guid'];
    if($isAW)
    {
        $description .= '<br /><a href="'.SERVICE_URL.'cache.php?show=aw&amp;guid='.$_GET['guid'].'">'.$lang['additional_waypoints'].'</a>';
        $urls .= ' '.SERVICE_URL.'cache.php?show=aw&guid='.$_GET['guid'];

        //parsing additional waypoints table
        $position = 0;
        $response = $oldResponse;
        $response = parseBetween('<strong>Additional Waypoints</strong>', '</table>');
        $table = array();
        $i = 0;
        while($position = strpos(' '.$response, '<tr')) {
            $allTable = $response;
            $position = 0;
            $tr = parseBetween('<tr bgcolor', '</tr>');
            $tr = substr($tr, (strpos($tr, '>')+1));
            $table[$i] = array();
            while($position = strpos(' '.$tr, '<td')) {
                $response = $tr;
                $position = 0;
                $td = parseBetween('<td', '</td>');
                $td = substr($td, (strpos($td, '>')+1));

                $table[$i][] = $td;
                $tr = substr($tr, (strpos($tr, '</td>')+5));
            }

            $response = substr($allTable, (strpos($allTable, '<tr bgcolor')+11));
            $response = substr($response, (strpos($response, '</tr>')+5));
            $i++;
        }
        foreach($table as $aw) {
            if(!empty($aw)&&isset($aw[3])) {
                $position = 0;
                $response = $aw[4];
                $urls .= ' '.SERVICE_URL.'aw.php?guid='.$_GET['guid'].'&lookup='.$aw[3];
            }
        }

    }
}
$html = "<b>".$lang['type']."</b>: ".$type."<br /><b>".$lang['difficulty']."</b>: ".$difficulty."<br /><b>".$lang['terrain']."</b>: ".$terrain."<br /><b>".$lang['size']."</b>: ".$size."<br /><b>".$lang['author']."</b>: ".$author."<br /><b>".$lang['waypoint']."</b>: ".$waypoint."<br /><b>".$lang['coordinates']."</b>:<br />".$coordinates."<br />";

//error if cache is archived or disabled
$error = '';
if(strpos($response, '<span id="ctl00_ContentBody_ErrorText"', $position)) {
    if (strpos($response, 'archived', $position)) {
        $error = $lang['archived'].'!';
    } elseif (strpos($response, 'unavailable', $position)) {
        $error = $lang['disabled'].'!';
    }
}

if(!empty($error)) {	//error output
    $html = '<?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            <html>
                <head>
                    <title>Error</title>
                </head>
                <body class="alert">
                    <p class="text">Cache '.$error.'</p>
                    <a href="locify://back" class="next">'.$lang['new_search'].'</a>
                <locify:timeout value="6000" />
                </body>
            </html>';
    echo $html;
} elseif($_GET['show'] == 'kml') {	//kml output, which Locify use for navigation
    Header('X-Cache-Store: '.$urls);
    $kml = '<?xml version="1.0" encoding="UTF-8"?>
            <kml xmlns="http://earth.google.com/kml/2.2">
                <Placemark>
                    <name><![CDATA['.$cacheName.']]></name>
                    <description><![CDATA['.$description.']]></description>
                    <Point>
                    <coordinates>'.$lon.','.$lat.'</coordinates>
                    </Point>
                    <ExtendedData>
                      <Data name="service">
                        <value>'.SERVICE_URL.'</value>
                      </Data>
                    </ExtendedData>
                </Placemark>
            </kml>';
    echo $kml;
} elseif($_GET['show'] == 'simple') {
    $out = '<?xml version="1.0" encoding="UTF-8"?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            <html>
                <head>
                    <title>'.$cacheName.'</title>
                </head>
                <body>
                     '.$html.'
                </body>
            </html>';
    echo $out;
}
?>
